import cv2
import numpy as np

def process_image(image_pil):
    # 将PIL图像转换为OpenCV格式
    img = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    # 初始化参数（针对红色文字优化）
    h_min, s_min, v_min = 0, 42, 199
    h_max, s_max, v_max = 25, 255, 255
    kernel_size_open_w, kernel_size_open_h = 1, 1  # 初始核尺寸（自动处理奇偶）
    kernel_size_close_w, kernel_size_close_h = 3, 3

    # 创建掩膜（针对红色文字优化）
    lower1 = np.array([h_min, s_min, v_min])
    upper1 = np.array([h_max, s_max, v_max])
    mask = cv2.inRange(hsv, lower1, upper1)

    # 创建形态学核
    kernel_open = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size_open_w, kernel_size_open_h))
    kernel_close = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size_close_w, kernel_size_close_h))

    # 形态学操作
    opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel_open)
    result_mask = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel_close)

    # 显示结果
    combined = cv2.bitwise_and(img, img, mask=result_mask)
    
    return combined